<?php
$template = file_get_contents('template_message.json');
$test_data = json_decode(file_get_contents('test_data.json'), true);
$openssl_config_template = file_get_contents('openssl.conf');

$messages = Array();

foreach ($test_data as $user) {
    while (strlen($user['id']) < 12) {
        $user['id'] = '0'.$user['id'];
    }
    $mac = implode(':', str_split($user['id'], 2));

    $lrs = '';
    for ($i=0; $i<100; $i++) {
        $lat = 47.32+rand(0,10000)/80000;
        $lon = 8.38+rand(0,10000)/35000;

        if (time()%2 == 0) {
            $lr = '{"latitude":'.$lat.','
                .'"longitude":'.$lon.','
                .'"accuracy":'.rand(0,100).','
                .'"timestamp":'.time().','
                .'"provider":"gps"}';
        }
        else {
            $lr = '{"latitude":'.$lat.','
                .'"longitude":'.$lon.','
                .'"accuracy":'.rand(0,100).','
                .'"timestamp":'.time().','
                .'"proovider":"gps"}';
        }

        usleep(10000);

        $lrs .= ','.$lr;
    }

    $lrs = substr($lrs, 1);

    file_put_contents(
      'openssl_'.$user['id'].'.conf',
      str_replace('[user_id]', intval($user['id']), $openssl_config_template)
    );

    $cmd = 'openssl req -config openssl_'.$user['id']
        .'.conf -new -newkey rsa '
        .'-keyout '.$user['id'].'_private_key.pem '
        .'-out '.$user['id'].'_csr.pem';

    exec($cmd);
    exec ('rm openssl_'.$user['id'].'.conf');

    $csr = '"'.base64_encode(file_get_contents($user['id'].'_csr.pem')).'"';

    $messages[] = str_replace(
      Array(
        '[access_token]',
        '[access_token_secret]',
        '[mac]',
        '[location_reports]',
        '[csr]'
      ),
      Array(
        $user['access_token'],
        $user['access_token_secret'],
        $mac,
        $lrs,
        $csr
      ),
      $template
    );
}

foreach ($messages as $message) {
    $content = utf8_encode('message='.$message);
    echo $content."\n";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://pc-10329-virt10.ethz.ch/api');
    // curl_setopt($ch, CURLOPT_URL, 'https://localhost/api');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array('Content-Type: application/x-www-form-urlencoded', 'Expect:'));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($ch);
    echo 'response='.$response."\n\n\n";

    print_r(json_decode($response, true));
    echo "\n\n\n";
}
?>
